package com.zzzy.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzzy.common.exception.WarningException;
import com.zzzy.common.util.CglibBeanCopierUtil;
import com.zzzy.sys.common.constant.MenuRootIdConstant;
import com.zzzy.sys.dao.entity.Menu;
import com.zzzy.sys.dao.mapper.MenuMapper;
import com.zzzy.sys.vo.menu.MenuTreeVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单权限 服务实现类
 *
 * @author fc
 * @since 2024-04-22
 */
@Service
public class MenuService extends ServiceImpl<MenuMapper, Menu> {

    public List<MenuTreeVO> getAllMenuTree() {
        return buildMenuTree(getAllMenu());
    }
    private List<MenuTreeVO> buildMenuTree(List<Menu> menuList) {
        List<MenuTreeVO> menuTreeVOList = CglibBeanCopierUtil.convertList(menuList, MenuTreeVO.class);
        // 构建菜单树
        Map<Long, MenuTreeVO> treeNodeMap = new LinkedHashMap<>();
        menuTreeVOList.forEach(menu -> {
            treeNodeMap.put(menu.getId(), menu);
        });
        // 处理父子关系
        treeNodeMap.values().stream().filter(node -> !node.getParentId().equals(MenuRootIdConstant.ID)).forEach(childNode -> {
            // 获得父节点
            MenuTreeVO parentNode = treeNodeMap.get(childNode.getParentId());
            if (Objects.isNull(parentNode)) {
                throw new WarningException(childNode.getId() + " 找不到父菜单");
            }
            // 将自己添加到父节点中
            if (CollectionUtils.isEmpty(parentNode.getChildren())) {
                parentNode.setChildren(new ArrayList<>());
            }
            parentNode.getChildren().add(childNode);
        });
        return treeNodeMap.values().stream().filter(node -> node.getParentId().equals(MenuRootIdConstant.ID)).collect(Collectors.toList());
    }

    public List<Menu> getAllMenu() {
        return baseMapper.selectList(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getParentId));
    }

    public List<Menu> getMenuListByRoleId(Long roleId) {
        return baseMapper.selectMenuListByRoleId(roleId);
    }

    public List<Menu> getMenuListByUserId(Long userId) {
        return baseMapper.selectMenuListByUserId(userId);
    }

    /**
     * 超级管理员只有系统设置相关权限
     */
    public List<Menu> getAdminMenu() {
        return baseMapper.selectAdminMenuList();
    }
}
